package org.softmed.rest.server.core.restlet;

import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.Server;
import org.restlet.data.Protocol;

public class RESTServer {
	int port = 8090;
	Protocol protocol = Protocol.HTTP;
	String path = "/";
	String rootURI;
	String mainPath;

	RESTletServerApplication application;
	Server server;
	Component component;
	Restlet root;

	public RESTServer(Protocol protocol, int port, String path, String rootURI) {
		this.rootURI = rootURI;
		this.protocol = protocol;
		this.port = port;
		this.path = path;

		buildMainPath();

		// Create a new Component.
		component = new Component();

		// Add a new HTTP server listening on port
		server = component.getServers().add(protocol, port);

		attachServerApplication();
	}

	public void attachServerApplication() {
		application = new RESTletServerApplication(component.getContext());

		// Attach the sample application.
		if (path == null)
			path = "";
		component.getDefaultHost().attach(path, application);
	}

	public void start() {
		try {

			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						component.start();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}).start();
		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	public void stop() {
		try {

			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						component.getDefaultHost().stop();
						component.stop();
						System.out.println("SERVER IS DOWN");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}).start();
		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	public Restlet getRoot() {
		return root;
	}

	public Server getServer() {
		return server;
	}

	public Component getComponent() {
		return component;
	}

	public int getPort() {
		return port;
	}

	public Protocol getProtocol() {
		return protocol;
	}

	public String getPath() {
		return path;
	}

	public RESTletServerApplication getApplication() {
		return application;
	}

	public void removeAllResources() {
		application.removeAllResources();
	}

	public String getMainPath() {
		return mainPath;
	}

	public String getRootURI() {
		return rootURI;
	}

	public void setRootURI(String root) {
		rootURI = root;
		buildMainPath();
	}

	protected void buildMainPath() {
		mainPath = protocol.toString().toLowerCase() + "://" + rootURI + ":"
				+ port;
	}

}
